"""
model name : MY_YOLO
file       : utils.py
information:
    author : OuYang
    time   : 2025/1/22
"""
import argparse

import torch


def calculate_padding(shape):
    w, h = shape
    if w > h:
        pad_h = (w - h) // 2
        return 0, pad_h, 0, pad_h
    elif h > w:
        pad_w = (h - w) // 2
        return pad_w, 0, pad_w, 0
    return 0, 0, 0, 0


def xywh2xyxy(xywh):
    """
    将(x, y, w, h) 的位置信息转化成为(x1, y1, x2, y2)
    """
    x, y, w, h = xywh

    x1 = x - w / 2
    y1 = y - h / 2
    x2 = x + w / 2
    y2 = y + h / 2

    return x1, y1, x2, y2


def select_optimizer(optim_name, model_parameters, **kwargs):
    if optim_name == 'SGD':
        return torch.optim.SGD(
            params=model_parameters,
            lr=kwargs['lr'],
            momentum=kwargs['momentum'],
            weight_decay=kwargs['weight_decay']
        )
    elif optim_name == 'Adam':
        return torch.optim.Adam(
            params=model_parameters,
            lr=kwargs['lr'],
            weight_decay=kwargs['weight_decay']
        )


def read_file_to_dict(file_path):
    data_dict = {}

    with open(file_path, 'r') as file:
        for line in file:
            key, value = line.strip().split('=')

            if value.isdigit():
                value = int(value)
            elif value.replace('.', '', 1).isdigit():
                value = float(value)
            else:
                value = value.strip('"')
            data_dict[key] = value

    return data_dict


def dict_to_arg_parser(config_dict):
    parser = argparse.ArgumentParser()

    for key, value in config_dict.items():
        parser.add_argument(f"--{key}", default=value)

    return parser.parse_args()

